// app/controller/delivery_controller.js
'use strict';

const Controller = require('egg').Controller;
const Joi = require('joi');

class DeliveryController extends Controller {
  // 获取发货订单列表
  async getDeliveryOrders() {
    const { ctx } = this;
    const { 
      page = 1, 
      limit = 20, 
      customerName,
      deliveryStatus,
      logisticsCompany,
      trackingNumber
    } = ctx.query;
    
    try {
      // 使用Joi验证服务进行参数验证
      const schema = Joi.object({
        page: Joi.number().integer().positive().optional(),
        limit: Joi.number().integer().positive().max(100).optional(),
        customerName: Joi.string().max(100).optional(),
        deliveryStatus: Joi.string().valid('pending', 'shipped', 'in_transit', 'delivered', 'exception').optional(),
        logisticsCompany: Joi.string().max(50).optional(),
        trackingNumber: Joi.string().max(50).optional()
      });
      
      const validation = schema.validate({
        page,
        limit,
        customerName,
        deliveryStatus,
        logisticsCompany,
        trackingNumber
      });
      
      if (validation.error) {
        ctx.error(`参数验证失败: ${validation.error.message}`);
        return;
      }
      
      // 构建查询条件
      const whereConditions = {};
      
      // 添加组织过滤条件
      if (ctx.state.organizationId) {
        whereConditions.organizationId = ctx.state.organizationId;
      }
      
      // 客户名称模糊查询
      if (customerName) {
        whereConditions.customerName = {
          [ctx.app.Sequelize.Op.like]: `%${customerName}%`
        };
      }
      
      // 发货状态查询
      if (deliveryStatus) {
        whereConditions.deliveryStatus = deliveryStatus;
      }
      
      // 物流公司查询
      if (logisticsCompany) {
        whereConditions.logisticsCompany = logisticsCompany;
      }
      
      // 物流单号查询
      if (trackingNumber) {
        whereConditions.trackingNumber = trackingNumber;
      }
      
      // 分页查询
      const offset = (parseInt(page) - 1) * parseInt(limit);
      const { rows, count } = await ctx.model.SalesOrderModel.findAndCountAll({
        where: whereConditions,
        limit: parseInt(limit),
        offset,
        order: [['order_date', 'DESC']]
      });
      
      // 转换数据格式
      const orders = rows.map(order => ({
        orderInfo: {
          platformOrderId: order.platformOrderId,
          amount: parseFloat(order.orderAmount),
          orderDate: order.orderDate,
          status: order.orderStatus
        },
        customerInfo: {
          name: order.customer ? order.customer.name : '',
          contactPerson: '', // 需要从客户联系人信息中获取
          phone: '', // 需要从客户联系人信息中获取
          email: '' // 需要从客户联系人信息中获取
        },
        logisticsInfo: {
          company: order.logisticsCompany || '',
          trackingNumber: order.trackingNumber || '',
          deliveryDate: order.deliveryDate || '',
          estimatedArrivalDate: order.estimatedArrivalDate || '',
          actualArrivalDate: order.actualArrivalDate || '',
          status: order.deliveryStatus || 'pending'
        }
      }));
      
      ctx.page(orders, count, parseInt(page), parseInt(limit));
    } catch (error) {
      ctx.logger.error('获取发货订单列表失败:', error);
      ctx.error(`获取发货订单列表失败: ${error.message}`);
    }
  }
  
  // 获取发货记录列表
  async getDeliveryRecords() {
    const { ctx } = this;
    const { orderId, page = 1, limit = 20 } = ctx.query;
    
    try {
      // 构建查询条件
      const whereConditions = {};
      
      // 添加组织过滤条件
      if (ctx.state.organizationId) {
        whereConditions.organizationId = ctx.state.organizationId;
      }
      
      // 根据订单ID查询
      if (orderId) {
        whereConditions.salesOrderId = orderId;
      }
      
      // 分页查询
      const offset = (parseInt(page) - 1) * parseInt(limit);
      const { rows, count } = await ctx.model.DeliveryRecordModel.findAndCountAll({
        where: whereConditions,
        limit: parseInt(limit),
        offset,
        order: [['created_at', 'DESC']]
      });
      
      ctx.page(rows, count, parseInt(page), parseInt(limit));
    } catch (error) {
      ctx.logger.error('获取发货记录列表失败:', error);
      ctx.error(`获取发货记录列表失败: ${error.message}`);
    }
  }
  
  // 获取发货记录详情
  async getDeliveryRecord() {
    const { ctx } = this;
    const { id } = ctx.params;
    
    try {
      const record = await ctx.model.DeliveryRecordModel.findByPk(id);
      
      if (!record) {
        ctx.error('发货记录不存在', 404);
        return;
      }
      
      ctx.success(record);
    } catch (error) {
      ctx.logger.error('获取发货记录详情失败:', error);
      ctx.error('获取发货记录详情失败');
    }
  }
  
  // 创建发货记录
  async createDeliveryRecord() {
    const { ctx } = this;
    const recordData = ctx.request.body;
    
    try {
      // 设置组织ID
      if (ctx.state.organizationId) {
        recordData.organizationId = ctx.state.organizationId;
      } else {
        recordData.organizationId = 1; // 默认组织ID
      }
      
      // 创建发货记录
      const record = await ctx.model.DeliveryRecordModel.create(recordData);
      ctx.success(record, '发货记录创建成功');
    } catch (error) {
      ctx.logger.error('创建发货记录失败:', error);
      ctx.error(`创建发货记录失败: ${error.message}`);
    }
  }
  
  // 更新发货记录
  async updateDeliveryRecord() {
    const { ctx } = this;
    const { id } = ctx.params;
    const recordData = ctx.request.body;
    
    try {
      const record = await ctx.model.DeliveryRecordModel.findByPk(id);
      
      if (!record) {
        ctx.error('发货记录不存在', 404);
        return;
      }
      
      await record.update(recordData);
      ctx.success(record, '发货记录更新成功');
    } catch (error) {
      ctx.logger.error('更新发货记录失败:', error);
      ctx.error('更新发货记录失败');
    }
  }
  
  // 删除发货记录
  async deleteDeliveryRecord() {
    const { ctx } = this;
    const { id } = ctx.params;
    
    try {
      const record = await ctx.model.DeliveryRecordModel.findByPk(id);
      
      if (!record) {
        ctx.error('发货记录不存在', 404);
        return;
      }
      
      await record.destroy();
      ctx.success(null, '发货记录删除成功');
    } catch (error) {
      ctx.logger.error('删除发货记录失败:', error);
      ctx.error('删除发货记录失败');
    }
  }
  
  // 获取发货统计信息
  async getDeliveryStats() {
    const { ctx } = this;
    
    try {
      // 添加组织过滤条件
      const orgWhere = {};
      if (ctx.state.organizationId) {
        orgWhere.organizationId = ctx.state.organizationId;
      }
      
      // 获取发货统计信息
      const total = await ctx.model.SalesOrderModel.count({
        where: {
          ...orgWhere,
          orderStatus: 'shipped'
        }
      });
      
      const pending = await ctx.model.SalesOrderModel.count({
        where: {
          ...orgWhere,
          orderStatus: 'paid'
        }
      });
      
      const delivered = await ctx.model.SalesOrderModel.count({
        where: {
          ...orgWhere,
          deliveryStatus: 'delivered'
        }
      });
      
      const exception = await ctx.model.SalesOrderModel.count({
        where: {
          ...orgWhere,
          deliveryStatus: 'exception'
        }
      });
      
      // 获取最近一周的发货趋势
      const oneWeekAgo = new Date();
      oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
      
      const weeklyStats = await ctx.model.SalesOrderModel.findAll({
        attributes: [
          [ctx.app.Sequelize.fn('DATE', ctx.app.Sequelize.col('delivery_date')), 'date'],
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count']
        ],
        where: {
          ...orgWhere,
          deliveryDate: {
            [ctx.app.Sequelize.Op.gte]: oneWeekAgo
          }
        },
        group: [ctx.app.Sequelize.fn('DATE', ctx.app.Sequelize.col('delivery_date'))],
        order: [[ctx.app.Sequelize.fn('DATE', ctx.app.Sequelize.col('delivery_date')), 'ASC']]
      });
      
      ctx.success({
        total,
        pending,
        delivered,
        exception,
        weeklyStats
      });
    } catch (error) {
      ctx.logger.error('获取发货统计信息失败:', error);
      ctx.error('获取发货统计信息失败');
    }
  }
}

module.exports = DeliveryController;